package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.dto.UltraGroupSwitchDTO;
import com.yami.shop.bean.model.MeltCloudGroup;
import com.yami.shop.bean.model.MeltCloudUltraGroupApply;
import com.yami.shop.bean.model.MeltCloudUltraGroupCost;
import com.yami.shop.bean.model.MeltCloudUltraGroupRecord;
import com.yami.shop.bean.vo.UltraGroupApplyVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.service.impl.RongYunGroupServiceImpl;
import com.yami.shop.vo.group.GroupVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/p/ultra/group")
@Tag(name = "app-融云超级群")
@AllArgsConstructor
public class MeltCloudUltraGroupController {

    private final MeltCloudUltraGroupApplyService ultraGroupApplyService;
    
    private final MeltCloudGroupService groupService;
    
    private final RongYunGroupServiceImpl rongYunGroupService;

    private final MeltCloudUltraGroupCostService ultraGroupCostService;

    private final MeltCloudUltraGroupRecordService ultraGroupRecordService;

    private final SysConfigService sysConfigService;
    
    @GetMapping("/apply/page")
    @Operation(summary =  "获取超级群组")
    public ServerResponseEntity<IPage<UltraGroupApplyVO>> getUltraGroupApply(PageParam<UltraGroupApplyVO> pageParam, @ParameterObject UltraGroupApplyVO applyVO) {
        YamiUser user = SecurityUtils.getUser();
        applyVO.setType(0);
        applyVO.setObjId(user.getUserId());
        IPage<UltraGroupApplyVO> page = ultraGroupApplyService.page(pageParam, applyVO);
        return ServerResponseEntity.success(page);
    }
    
    @GetMapping("/record/list")
    @Operation(summary =  "超级群记录")
    public ServerResponseEntity<List<MeltCloudUltraGroupRecord>> list(@RequestParam Long applyId){
        List<MeltCloudUltraGroupRecord> list = ultraGroupRecordService.list(Wrappers.lambdaQuery(MeltCloudUltraGroupRecord.class)
                .eq(MeltCloudUltraGroupRecord::getGroupApplyId, applyId).orderByDesc(MeltCloudUltraGroupRecord::getCreateTime).orderByDesc(MeltCloudUltraGroupRecord::getId));
        return ServerResponseEntity.success(list);
    }

    @PostMapping("/create")
    @Operation(summary =  "申请创建超级群组")
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<MeltCloudGroup> create(@RequestBody GroupVo groupVo) {
        if (groupVo.getType() != 1) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "只可创建超级群聊！");
        }
        if (Objects.isNull(groupVo.getCostId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "请选择超级群资费套餐！");
        }
        YamiUser user = SecurityUtils.getUser();
        MeltCloudUltraGroupApply apply = MeltCloudUltraGroupApply.builder()
                .type(0).costId(groupVo.getCostId()).objId(user.getUserId()).name(groupVo.getGroupName()).pic(groupVo.getPic()).isOfficial(0)
                .build();
        UltraGroupSwitchDTO ultraGroupSwitch = sysConfigService.getSysConfigObject(Constant.ULTRA_GROUP_SWITCH, UltraGroupSwitchDTO.class);
        if (!ultraGroupSwitch.getUserAudit()) {
            // 免审核-扣减gas-创建
            apply.setStatus(3);
            ultraGroupApplyService.save(apply);
            rongYunGroupService.reduceGasAndCreateGroup(apply, true);
        } else {
            ultraGroupApplyService.save(apply);
        }
        return ServerResponseEntity.success();
    }


    @GetMapping("/apply/getById")
    @Operation(summary =  "超级群申请详情")
    public ServerResponseEntity<MeltCloudUltraGroupApply> apply(@RequestParam Long applyId){
        MeltCloudUltraGroupApply apply = ultraGroupApplyService.getById(applyId);
        return ServerResponseEntity.success(apply);
    }


    @PostMapping("/apply/edit")
    @Operation(summary =  "新增超级群申请")
    public ServerResponseEntity update(@RequestBody @Valid MeltCloudUltraGroupApply apply){
        MeltCloudUltraGroupApply one = ultraGroupApplyService.getById(apply.getId());
        if (one.getStatus() == 3) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群已创建不能修改！");
        }
        apply.setStatus(0);
        ultraGroupApplyService.updateById(apply);
        return ServerResponseEntity.success();
    }
    

    @PostMapping("/renew")
    @Operation(summary =  "超级群续费")
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity renew(@RequestBody MeltCloudUltraGroupApply apply){
        MeltCloudUltraGroupApply one = ultraGroupApplyService.getOne(Wrappers.lambdaQuery(MeltCloudUltraGroupApply.class).eq(MeltCloudUltraGroupApply::getType, 0).eq(MeltCloudUltraGroupApply::getGroupId, apply.getGroupId()));
        if (one.getStatus() != 3)
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群未成功创建！");
        MeltCloudGroup group = groupService.getById(apply.getGroupId());
        if (group == null)
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群不存在！");
        if (!group.getType().equals("1"))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "只有超级群需要续费！");
        if (group.getIsDismiss().equals("1"))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群已解散！");
        if (Objects.isNull(apply.getCostId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "请选择超级群资费套餐！");
        }
        one.setName(group.getGroupName());
        one.setPic(group.getPics());
        one.setIsOfficial(0);
        one.setCostId(apply.getCostId());
        rongYunGroupService.reduceGasAndCreateGroup(one, false);
        return ServerResponseEntity.success();
    }


    @GetMapping("/cost/list")
    @Operation(summary =  "获取超级群聊资费标准", description = "获取超级群聊资费标准")
    public ServerResponseEntity<List<MeltCloudUltraGroupCost>> list(){
        List<MeltCloudUltraGroupCost> list = ultraGroupCostService.list(Wrappers.lambdaQuery(MeltCloudUltraGroupCost.class)
                .eq(MeltCloudUltraGroupCost::getIsHide, 0).eq(MeltCloudUltraGroupCost::getIsDel, 0).orderByAsc(MeltCloudUltraGroupCost::getMonths).orderByAsc(MeltCloudUltraGroupCost::getEnergyValue));
        return ServerResponseEntity.success(list);
    }


    @GetMapping("/cancel/renewal")
    @Operation(summary =  "取消自动续费")
    public ServerResponseEntity cancelAutoRenewal(@RequestParam Long groupId) {
        return rongYunGroupService.cancelAutoRenewal(groupId);
    }
    
    
    @GetMapping("/expire/operate")
    @Operation(summary =  "超级群到期操作权限")
    public ServerResponseEntity operationExpireCheck(@RequestParam String groupId) {
        Boolean check = rongYunGroupService.ultraGroupExpireCheck(groupId, null, true);
        return ServerResponseEntity.success(check);
    }
    
    
    
}
